﻿using B.S.BaseData.Domain.Entities.RBAC;

namespace B.S.BaseData.ReadAPI.Utils
{
    public class CustomAuthorizationMiddleware
    {
        private readonly RequestDelegate _next;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        public CustomAuthorizationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        /// <summary>
        /// 自定义授权中间件
        /// </summary>
        /// <param name="context"></param>
        public async Task InvokeAsync(HttpContext context)
        {
            // 通过 HttpContext 解析 TokenHelper
            var tokenHelper = context.RequestServices.GetRequiredService<TokenHelper>();

            //拿到请求路径
            var path = context.Request.Path;

            //这里可以判断是否需要验证token

            // 拿到请求头的 token
            var token = context.Request.Headers["Authorization"].ToString().Replace("Bearer ", "");

            if (!string.IsNullOrEmpty(token))
            {
                var userinfo = tokenHelper.ConvertTokenToObj<User>(token);
            }
            // 调用下一个中间件
            await _next(context);
        }
    }
}
